package com.himiotech.core.project.web.system;

import com.himiotech.core.framework.config.HimioConfig;
import com.himiotech.core.framework.config.shiro.service.PasswordService;
import com.himiotech.core.framework.helper.anno.Log;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.enums.BusinessType;
import com.himiotech.core.framework.helper.utils.DateUtils;
import com.himiotech.core.framework.helper.utils.file.FileUploadUtils;
import com.himiotech.core.framework.helper.utils.file.FileUtils;
import com.himiotech.core.project.model.entity.user.User;
import com.himiotech.core.project.service.IUserService;
import com.himiotech.core.project.web.base.HimioBaseController;
import com.himiotech.core.project.web.base.model.HimioResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Slf4j
@Controller
@RequestMapping("/system/profile")
public class ProfileController extends HimioBaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordService passwordService;

    /**
     * 个人信息
     */
    @GetMapping
    public String profile(ModelMap mmp) {
        User user = getSysUser();
        mmp.put("user", user);
        mmp.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
        mmp.put("postGroup", userService.selectUserPostGroup(user.getUserId()));
        return "system/profile";
    }


    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public HimioResult resetPwd(String oldPassword, String newPassword) {
        User user = getSysUser();
        if (!passwordService.matches(user, oldPassword)) {
            return writeJsonErr("修改密码失败，旧密码错误");
        }
        if (passwordService.matches(user, newPassword)) {
            return writeJsonErr("新密码不能与旧密码相同");
        }
        user.setPassword(newPassword);
        user.setPwdUpdateDate(DateUtils.getNowDate());
        if (userService.resetUserPwd(user) > 0) {
            setSysUser(userService.getById(user.getUserId()));
            return writeJsonOk();
        }
        return writeJsonErr("修改密码异常，请联系管理员");
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ResponseBody
    public HimioResult update(User user) {
        User currentUser = getSysUser();
        currentUser.setUserName(user.getUserName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhoneNumber(user.getPhoneNumber());
        currentUser.setSex(user.getSex());
        currentUser.setRemark(user.getRemark());
        if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(currentUser))) {
            return writeJsonErr("修改用户'" + currentUser.getLoginName() + "'失败，邮箱账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhoneNumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(currentUser))) {
            return writeJsonErr("修改用户'" + currentUser.getLoginName() + "'失败，手机号码已存在");
        }
        if (userService.updateById(currentUser)) {
            setSysUser(userService.getById(currentUser.getUserId()));
            return writeJsonOk();
        }
        return writeJsonErr();
    }

    /**
     * 保存头像
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAvatar")
    @ResponseBody
    public HimioResult updateAvatar(@RequestParam(value = "avatarFile", required = false) MultipartFile file, @RequestParam(value = "avatarBase64", required = false) String base64) {
        User currentUser = getSysUser();
        try {
            if (StringUtils.isNotEmpty(base64) && base64.startsWith("data:")) {
                file = FileUtils.base64ToMultipartFile(base64);
            }
            if (!file.isEmpty()) {
                String avatar = FileUploadUtils.upload(HimioConfig.getAvatarPath(), file);
                currentUser.setAvatar(avatar);
                if (userService.updateById(currentUser)) {
                    setSysUser(userService.getById(currentUser.getUserId()));
                    return writeJsonOk();
                }
            }
            return writeJsonErr();
        } catch (Exception e) {
            log.error("修改头像失败！", e);
            return writeJsonErr(e.getMessage());
        }
    }
}
